<!DOCTYPE html>
<html ang="en" class="no-js" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>好友列表</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>

<!--用户列表显示-->
<table id="userTable" lay-filter="userFilter"></table>
<!--用户更新form-->
<form id="userUpdateForm" class="layui-form" lay-filter="userUpdateFilter" style="display: none">
    <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
    <input type="hidden" name="userId">

    <div class="layui-form-item">
        <label class="layui-form-label">登陆账号</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" placeholder="loginName" required lay-verify="required"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户昵称</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">电子邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" placeholder="请输入" autocomplete="off"
                   lay-verify="email" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="text" name="phonenumber" placeholder="请输入" autocomplete="off"
                   lay-verify="phone" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked>
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <div class="layui-input-block">
        <button type="button" class="layui-btn layui-btn-normal" id="uploadFile">
            <i class="layui-icon">&#xe67c;</i>上传图片
        </button>
    </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="如需更新 请输入新密码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block">
            <input th:each="role:${session.roleList}" type="checkbox"
                   name="roleNames" lay-skin="primary" th:title="${role.roleName}"
                   th:value="${role.roleName}">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">账号状态</label>
        <div class="layui-input-block">
            <input type="radio" name="status" value="0" title="正常" checked>
            <input type="radio" name="status" value="1" title="停用">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <input type="text" name="remark" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="userUpdateFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-normal">重置</button>
        </div>
    </div>
</form>
<!--用户添加form-->
<form id="userAddForm" class="layui-form" style="display: none"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
    <div class="layui-form-item">
        <label class="layui-form-label">部门名称</label>
        <div class="layui-input-block">
            <select name="deptId" lay-filter="dept">
                <option th:each="dept:${session.deptList}"
                        th:value="${dept.getDeptId}" th:text="${dept.getDeptName}">
                </option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">登陆账号</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" placeholder="请输入" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户昵称</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block">
            <input th:each="role:${session.roleList}" type="checkbox"
                   name="roleNames" lay-skin="primary" th:title="${role.roleName}"
                   th:value="${role.roleName}">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">电子邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" placeholder="请输入" autocomplete="off"
                   lay-verify="email" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="text" name="phonenumber" placeholder="请输入" autocomplete="off"
                   lay-verify="phone" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked>
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">头像</label>
        <input type="hidden" name="avatar" id="avatar">
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-normal" id="uploadFile">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="请输入" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">账号状态</label>
        <div class="layui-input-block">
            <input type="radio" name="status" value="0" title="正常" checked>
            <input type="radio" name="status" value="1" title="停用">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <input type="text" name="remark" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="userAddFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-normal">重置</button>
        </div>
    </div>
</form>
<!--行编辑工具栏-->
<script type="text/html" id="barRowEdit">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">查看主页</a>
</script>
<!--头部工具栏-->
<script type="text/html" id="toolbarHead">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="delete">删除</button>
    </div>
</script>


<!--JavaScript代码区域-->
<script src="/layui/layui.js"></script>
<!--列表信息显示-->
<script>
    layui.use(['table', 'layer', 'form', 'jquery', 'upload'], function () {
        let table = layui.table;//数据表格模块
        let layer = layui.layer;//弹出层模块
        let form = layui.form;//表单模块
        let $ = layui.jquery;
        let upload = layui.upload;
        let $roleCheckBox = $("div[name=roles]");

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadFile' //绑定元素
            , url: '/user/uploadHeadPic' //上传接口
            , auto: true // 选择文件后自动上传
            , field: "headPic"
            , done: function (res) {
                // layer.msg(JSON.stringify(res));
                //上传完毕回调
                if (res.code == 0) {
                    $("#avatar").val(res.data.filePath);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });

        //用户列表
        let userTable = table.render({
            elem: '#userTable' //table标签的id
            , toolbar: '#toolbarHead'//开启头部工具栏，并为其绑定左侧模板
            , url: '/friends/queryAllFriends' //数据接口
            , page: true //开启分页，默认向后台发两个参数page和limit
            // , cellMinWidth: 45//自适应宽度，最短为80
            , cols: [
                [ //表头 两个中括号不能在同一行，与thymeleaf语法冲突
                    {type: 'checkbox', fixed: 'left'} //开启复选框，必须有fixed
                    , {field: 'deptId', title: '部门ID', sort: true, width: 90}
                    , {field: 'loginName', title: '账号', width: 90}
                    , {field: 'userName', title: '昵称'}
                    , {field: 'email', title: '电子邮箱'}
                    , {field: 'phonenumber', title: '手机号'}
                    , {
                    field: 'sex', title: '性别',
                    templet: function (d) {
                        return d.status == 0 ? "男" : "女"
                    }, sort: true, width: 50
                }
                    , {field: 'avatar', title: '头像'}
                    , {
                    field: 'status', title: '账号状态',
                    templet: function (d) {
                        return d.status == 0 ? "正常" : "停用"
                    }, sort: true, width: 60
                }
                    , {field: 'remark', title: '备注', width: 80},
                    {fixed: 'right', title: '操作', align: 'center', toolbar: '#barRowEdit', width: 120}
                ]
            ]
        });
        //行编辑工具栏监听事件
        table.on('tool(userFilter)', function (obj) {
            //获取当前行数据
            let data = obj.data;
            //判断是删除还是编辑
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    //向后台发送异步请求
                    $.ajax({
                        url: "/user/deleteById",
                        type: "DELETE",
                        data: {userId: data.userId},
                        dataType: "json",
                        success: function (resp) {
                            if (resp.code == 0) {
                                layer.msg(resp.msg);
                                //重新加载数据
                                userTable.reload({
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                })
                            }
                        },
                        error: function (e) {
                            layer.msg("请求失败");
                        }
                    });
                });
            } else if (obj.event === 'edit') {

                //复选框回显
                /*$.ajax({
                    url: "/user/findSelectRole",
                    type: "GET",
                    dataType: "JSON",
                    data: {roleId: data.roleId},
                    success: function (ret) {
                        for (let i = 0; i < ret.length; i++) {
                            for (let j = 0; j < $input.length; j++) {
                                if ($input[j].value == ret[i]) {
                                    $input[j].checked = true
                                }
                            }
                        }
                        //重新渲染
                        form.render()
                    }
                })*/

                //表单赋值，取值 这里是赋值
                form.val("userUpdateFilter", data);
                //打开弹出层
                layer.open({
                    type: 1,//指页面层
                    area: ['500px', '550px'],
                    content: $('#userUpdateForm') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                });

            }
        });
        //头部工具栏监听事件
        table.on('toolbar(userFilter)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let checkData = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    //重置form表单
                    document.getElementById("userAddForm").reset();
                    layer.open({
                        type: 1,
                        area: ['400px', '550px'],
                        content: $('#userAddForm') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    break;
                case 'delete':
                    //判断是否选中行
                    if (checkData.length == 0) {
                        layer.msg('请至少选择一行数据');
                        return;
                    }
                    layer.confirm('真的删除行么', function (index) {
                        //获取所有选中行id
                        let userIds = "";
                        for (let i = 0; i < checkData.length; i++) {
                            userIds += checkData[i].userId + ",";
                        }
                        ;
                        userIds = userIds.substr(0, userIds.length - 1);
                        layer.msg(userIds);
                        //调用批量删除
                        $.ajax({
                            url: "/user/deleteByIds",
                            type: "DELETE",
                            data: {userIds: userIds},
                            dataType: "json",
                            success: function (resp) {
                                if (resp.code == 0) {
                                    layer.msg(resp.msg);
                                    //重新加载数据
                                    userTable.reload();
                                }
                            },
                            error: function (e) {
                                layer.msg("请求失败");
                            }
                        });
                    });
                    break;
            }
            ;
        });

        //更新(编辑)的监听事件
        form.on('submit(userUpdateFilter)', function (data) {
            layer.msg(JSON.stringify(data.field));

            if ($("input:checkbox[name='roleNames']:checked").length == 0) {
                return;
            }
            //获取checkbox[name='level']的值，获取所有选中的复选框，并将其值放入数组中
            var arr = new Array();
            $("input:checkbox[name='roleNames']:checked").each(function (i) {
                arr[i] = $(this).val();
            });
            data.field.roleNames = arr;//将数组合并成字符串

            $.ajax({
                url: "/user/update",
                type: "PUT",
                data: data.field,
                dataType: "json",
                success: function (resp) {
                    if (resp.code == 0) {
                        layer.msg(resp.msg);
                        //关闭弹框
                        layer.closeAll('page');
                        //重新加载数据
                        userTable.reload();
                    }
                },
                error: function (e) {
                    layer.msg("请求失败");
                }
            });
            return false;
        });
        //添加监听事件
        form.on('submit(userAddFilter)', function (data) {
            layer.msg(JSON.stringify(data.field));

            if ($("input:checkbox[name='roleNames']:checked").length == 0) {
                return;
            }
            //获取checkbox[name='level']的值，获取所有选中的复选框，并将其值放入数组中
            var arr = new Array();
            $("input:checkbox[name='roleNames']:checked").each(function (i) {
                arr[i] = $(this).val();
            });
            data.field.roleNames = arr;//将数组合并成字符串

            $.ajax({
                url: "/user/insert",
                type: "POST",
                data: data.field,
                dataType: "json",
                success: function (resp) {
                    if (resp.code == 0) {
                        layer.msg(resp.msg);
                        //关闭弹框
                        layer.closeAll('page');
                        //重新加载数据
                        userTable.reload();
                    }
                },
                error: function (e) {
                    layer.msg("请求失败");
                }
            });
            return false;
        });
        //顶部搜索框监听事件
        form.on('submit(searchFilter)', function (data) {
            //执行重载
            userTable.reload({
                where: {
                    deptId: data.field.deptId,
                    loginName: data.field.loginName,
                    userName: data.field.userName
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        //重置条件查询表单，刷新table数据
        $("#myButton").click(function () {
            userTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    deptId: ""
                    , loginName: ""
                    , userName: ""
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
    });
</script>
</body>
</html>